package com.gz.service;

import com.gz.common.Message;
import com.gz.common.MessageType;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SendFileServer {
    //发送文件
    public  void sendMessagetoOne_file(String senderfilepath,String receiverfilepath,String sender,String receiver){
        Message message = new Message();
        message.setSender(sender);
        message.setReceiver(receiver);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formatedDate = simpleDateFormat.format(new Date());
        message.setSendTime(formatedDate);
        message.setMestype(MessageType.MESSAGE_FILE_MES);
        message.setFilepath(receiverfilepath);
        FileInputStream fileInputStream=null;
        byte[] filebytes=new byte[(int)new File(senderfilepath).length()];
        try {
            fileInputStream = new FileInputStream(senderfilepath);
            fileInputStream.read(filebytes);
            message.setFilebytes(filebytes);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileInputStream!=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            try {
                ObjectOutputStream oos = new ObjectOutputStream(
                        MangeClientConnectServerThread.getClientConnectServerThread(
                                sender).getSocket().getOutputStream());
                oos.writeObject(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
